import {
  getProductQualityByPage,
  updateProductQuality,
  delProductQuality,
  exportProductQuality,
  getWorkOrderInforList,
  getQualityTeamMembers,
  getInspectionStandard,
  getInspectionTemplateByProductTypeAndType,
  viewBaseInfo,
  stagingInspectionTask,
  submitInspectionTask,
  getProductQualityInspectionAllInfoByProductQualityId,
  getProductQualityInspectionByPage,
} from '@/services/quality/productQuality';
import { getProductTypeList } from '@/services/templateMaintain/inspectionTemplate';
import { PlusOutlined, CheckCircleOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import ReactToPrint from 'react-to-print';
import {
  Button,
  Form,
  Input,
  message,
  Modal,
  Select,
  Table,
  Tabs,
  Row,
  Col,
  Radio,
  Checkbox,
  Descriptions,
  Space,
} from 'antd';
import { Ellipsis } from '@/components/Ellipsis';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import dayjs from '@/components/dayjs';
import type { ColumnsType } from 'antd/es/table';
import type { DataType, tabType, record_quality_Type } from './components/interfacequality';
import './thepagestyle.less';
import InspectionFileInfo from './inspectionFileInfo';
import moment from 'moment';
import { center } from '@antv/g2plot/lib/plots/sankey/sankey';
import { tableSearchPublicConfig } from '@/utils/filterUtils';
import { stubFalse } from 'lodash';
const ProductQuality: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const actionRef_2 = useRef<ActionType>();
  const actionRef_3 = useRef<ActionType>();
  const [modalVisit2, setModalVisit2] = useState(false); // 新建和编辑提示框
  const [confirmLoading2, setConfirmLoading2] = useState(false); //编辑框的disable
  const [thewo, setthewo] = useState([]); //工单下拉框
  const [themember, setthemember] = useState([]); //成员下拉框
  const [theinspector, settheinspector] = useState(''); //检验人
  const [theuserid, settheuserid] = useState(''); //userid
  const [standardTableList, setstandardTableList] = useState([]); //userid

  const [open, setOpen] = useState(false); //控制查看Modal的开关
  const [submit_open, setsubmit_open] = useState(false); //确认检验的弹窗开关
  const [confirmLoading3, setConfirmLoading3] = useState(false);
  const [quality_Record, setquality_Record] = useState<record_quality_Type>();
  const styleCommon = { fontSize: 16, marginBottom: 20 }; //定义一个样式
  const [thehead, setthehead] = useState([]); //预览用，保存表头
  const [theitem, settheitem] = useState([]); //预览用，保存项
  const [thetitle, setthetitle] = useState('');
  const [thetitleInfo, setTitileInfo] = useState([]);
  const values: any[] = [];

  const [select_id, setselect_id] = useState('');

  const { TextArea } = Input;
  const [currentmemberid, setcurrentmemberid] = useState('');

  const dateFormat = 'YYYY-MM-DD HH:mm';
  const [form] = Form.useForm();
  const ref = useRef(null);
  //触发打印按钮
  const componentRef = useRef();

  // 待检验
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      sorter: true,
      width: 80,
    },
    {
      title: '工单编号',
      dataIndex: 'wo',
      align: 'center',
      sorter: true,
      width: 215,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '项目编号',
      dataIndex: 'projectCode',
      align: 'center',
      sorter: true,
      width: 145,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      align: 'center',
      sorter: true,
      width: 160,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '批次编号',
      dataIndex: 'batchPlanCode',
      align: 'center',
      sorter: true,
      width: 200,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '当前批次',
      dataIndex: 'currentBatchCode',
      align: 'center',
      sorter: true,
      width: 100,
      search: false,
      // render: (text) => <>{Ellipsis(text)}</>,
      render: (text, record) => (
        <div>
          {text}/{record.batchCount}
        </div>
      ),
    },
    {
      title: '柜体类型',
      dataIndex: 'productType',
      align: 'center',
      sorter: true,
      width: 110,
      render: (text) => <>{Ellipsis(text)}</>,
      valueType: 'select',
      request: async () => {
        const getproduct = await getProductTypeList(null);
        const productOptionContract: any[] = [];
        getproduct.data.map((item: any, index: any) => {
          productOptionContract.push({ value: item, label: item });
        });
        return productOptionContract;
      },
    },
    {
      title: '柜体编号',
      dataIndex: 'productCode',
      align: 'center',
      sorter: true,
      width: 215,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '柜体描述',
      dataIndex: 'productDesc',
      align: 'center',
      sorter: true,
      width: 160,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '检验状态',
      dataIndex: 'status',
      render: (text, record, _, action) => {
        return (
          <div>{record.status == 1 ? '已检验' : record.status == -1 ? '再检验' : '待检验'}</div>
        );
      },
      width: 110,
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '检验结果',
      dataIndex: 'inspection',
      align: 'center',
      sorter: true,
      search: false,
      render: (text, record, _, action) => {
        return (
          <div>
            {record.inspection == null
              ? '-'
              : record.inspection == '1'
              ? '合格'
              : record.inspection == '2'
              ? '让步接收'
              : '不合格'}
          </div>
        );
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 120,
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="editKey1"
          onClick={async () => {
            setquality_Record(record);
            // 获取模板
            const template_result = await getProductQualityInspectionAllInfoByProductQualityId({
              productQualityId: record.id,
            });
            if (template_result != undefined && template_result != null) {
              setTitileInfo(template_result.data.inspectionInfoAllEx.inspectionTask); //检验表信息
              setthetitle(template_result.data.inspectionInfoAllEx.inspectionTask.templateName);
              setthehead(template_result.data.inspectionInfoAllEx.inspectionCostomValueExList);
              settheitem(template_result.data.inspectionInfoAllEx.inspectionItemExList);
            }
            setOpen(true);
            setselect_id(record.id);
          }}
        >
          入厂检验
        </a>,
        // <a
        //   key="deleteKey1"
        //   onClick={() => {
        //     Modal.confirm({
        //       title: '删除',
        //       content: '确定要删除吗',
        //       okText: '确认',
        //       cancelText: '取消',
        //       onOk: async () => {
        //         await delProductQuality({ id: record.id });
        //         actionRef.current!.reload();
        //       },
        //     });
        //   }}
        // >
        //   删除
        // </a>,
      ],
    },
  ];

  //检验通过
  const tested_columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      sorter: true,
      width: 80,
    },
    {
      title: '工单编号',
      dataIndex: 'wo',
      width: 215,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '项目编号',
      dataIndex: 'projectCode',
      width: 145,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      align: 'center',
      sorter: true,
      width: 160,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '批次编号',
      dataIndex: 'batchPlanCode',
      width: 200,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '当前批次',
      dataIndex: 'currentBatchCode',
      width: 100,
      align: 'center',
      sorter: true,
      search: false,
      // render: (text) => <>{Ellipsis(text)}</>,
      render: (text, record) => (
        <div>
          {text}/{record.batchCount}
        </div>
      ),
    },
    {
      title: '柜体类型',
      dataIndex: 'productType',
      width: 110,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
      valueType: 'select',
      request: async () => {
        const getproduct = await getProductTypeList(null);
        const productOptionContract: any[] = [];
        getproduct.data.map((item: any, index: any) => {
          productOptionContract.push({ value: item, label: item });
        });
        return productOptionContract;
      },
    },
    {
      title: '柜体编号',
      dataIndex: 'productCode',
      width: 215,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '柜体描述',
      dataIndex: 'productDesc',
      align: 'center',
      sorter: true,
      width: 160,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '检验状态',
      dataIndex: 'status',
      render: (text, record, _, action) => {
        return (
          <div>{record.status == 1 ? '已检验' : record.status == -1 ? '再检验' : '待检验'}</div>
        );
      },
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '检验结果',
      dataIndex: 'inspection',
      align: 'center',
      sorter: true,

      search: false,
      render: (text, record, _, action) => {
        return (
          <div>
            {record.inspection == null
              ? '-'
              : record.inspection == '1'
              ? '合格'
              : record.inspection == '2'
              ? '让步接收'
              : '不合格'}
          </div>
        );
      },
    },
    {
      title: '检验备注',
      dataIndex: 'memo',
      align: 'center',
      sorter: true,
      search: false,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '检验人',
      dataIndex: 'inspector',
      align: 'center',
      sorter: true,
      search: false,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '检验时间',
      dataIndex: 'inspectTime',
      align: 'center',
      sorter: true,
      search: false,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 120,
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="editKey2"
          onClick={async () => {
            setquality_Record(record);
            setselect_id(record.id);
            // 获取模板
            const template_result = await getProductQualityInspectionAllInfoByProductQualityId({
              productQualityId: record.id,
            });
            if (template_result != undefined && template_result != null) {
              setTitileInfo(template_result.data.inspectionInfoAllEx.inspectionTask); //检验表信息
              setthetitle(template_result.data.inspectionInfoAllEx.inspectionTask.templateName);
              setthehead(template_result.data.inspectionInfoAllEx.inspectionCostomValueExList);
              settheitem(template_result.data.inspectionInfoAllEx.inspectionItemExList);
            }
            setOpen(true);
          }}
        >
          检验详情
        </a>,
        // <a
        //   key="deleteKey2"
        //   onClick={() => {
        //     Modal.confirm({
        //       title: '删除',
        //       content: '确定要删除吗',
        //       okText: '确认',
        //       cancelText: '取消',
        //       onOk: async () => {
        //         await delProductQuality({ id: record.id });
        //         actionRef_2.current!.reload();
        //       },
        //     });
        //   }}
        // >
        //   删除
        // </a>,
      ],
    },
  ];

  //检验标准列表
  const standardColumns: ColumnsType<DataType> = [
    {
      title: '检验点',
      dataIndex: 'inspectionItem',
      key: 'inspectionItem',
      align: 'center',
      sorter: true,
    },
    {
      title: '检验标准',
      dataIndex: 'inspectionStandard',
      key: 'inspectionStandard',
      //align: 'center',sorter: true,
    },
  ];

  // 确认检验：是否合格
  const inspection_Submit = async () => {
    setConfirmLoading3(true);
    form
      .validateFields()
      .then(async () => {
        const result_template = await submitInspectionTask({
          inspectionCostomValueDtoList: thehead,
          inspectionItemDtoList: theitem,
          inspectionTask: thetitleInfo,
        });
        // 检验结果提交，是否合格
        const res = form.getFieldsValue();
        res.memo = thetitleInfo.memo;
        res.wo = quality_Record?.wo;
        res.projectCode = quality_Record?.projectCode;
        res.batchPlanCode = quality_Record?.batchPlanCode;
        res.currentBatchCode = quality_Record?.currentBatchCode;
        res.productType = quality_Record?.productType;
        res.productCode = quality_Record?.productCode;
        res.id = quality_Record?.id;
        res.inspectorId = currentmemberid;
        res.inspectTime = moment().format('YYYY-MM-DD HH:mm:ss'); //精确到秒
        res.status = res.inspection == 1 ? 1 : -1;
        res.inspectionTaskId = quality_Record?.inspectionTaskId;
        res.productId = quality_Record?.productId;
        res.productDesc = quality_Record?.productDesc;
        res.projectId = quality_Record?.projectId;
        res.projectName = quality_Record?.projectName;
        res.batchCount = quality_Record?.batchCount;
        console.log(res, '检验结果');
        const result = await updateProductQuality(res);
        if (result != null) {
          message.success('检验成功');
          setConfirmLoading3(false);
          setsubmit_open(false);
          // setOpen(false);
          actionRef.current!.reload();
          actionRef_2.current!.reload();
          actionRef_3.current!.reload();
        }
      })
      .catch(() => {
        setConfirmLoading3(false);
      });
  };

  // 获取下拉框内容
  const getlist = async () => {
    // 工单
    const getwo = await getWorkOrderInforList(null);
    const woOptionContract = [];
    getwo.data.map((item: any, index: any) => {
      woOptionContract.push({ value: item.wo, label: item.wo });
    });
    setthewo(woOptionContract);
    // 成员
    // const getmember = await getQualityTeamMembers(null);
    // const memberOptionContract = [];
    // getmember.data.map((item: any, index: any) => {
    //   memberOptionContract.push({ value: item.id, label: item.name});
    // });
    // setthemember(memberOptionContract);
  };

  //取消检验列表Modal的弹窗
  const handleCancel = () => {
    setModalVisit2(false);
  };

  //取消编辑Modal的弹窗
  const edit_handleCancel = () => {
    setOpen(false);
    setthehead([]);
    settheitem([]);
    setthetitle('');
  };

  // 检验清单暂存
  const handleSave_template = async () => {
    const result = await stagingInspectionTask({
      inspectionCostomValueDtoList: thehead,
      inspectionItemDtoList: theitem,
      inspectionTask: thetitleInfo,
    });
    if (result && result.code === 0) {
      message.success('保存成功');
    }
  };

  // 打印检验单，需要重新调整格式
  const print_template = async () => {
    // 可打印，但页眉页脚没去掉
    // var iframe = document.createElement('iframe'); //通过iframe进行打印机打印
    // iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:0px;top:0px;');
    // document.body.appendChild(iframe);
    // var iframeDocument = iframe.contentWindow.document;
    // iframeDocument.body.innerHTML = document.getElementById('templatebox').innerHTML;
    // iframeDocument.close();
    // iframe.contentWindow.print();

    // 去掉页眉页脚，但样式不美观
    const el = document.getElementById('templatebox');
    const iframe = document.createElement('IFRAME');
    let doc = null;
    iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:500px;top:500px; margin-top:100px');
    document.body.appendChild(iframe);
    doc = iframe.contentWindow.document;    
    // 打印时去掉页眉页脚
    doc.write('<style media="print">@page {size: auto;  margin: 8mm; }</style>');
    doc.write(el.innerHTML);
    doc.close();
    // 获取iframe的焦点，从iframe开始打印
    iframe.contentWindow.focus();
    iframe.contentWindow.print();
    if (navigator.userAgent.indexOf("MSIE") > 0) {
      document.body.removeChild(iframe);
    }
  };


  //定义页面Tabs的子结构的数组
  const tabList: tabType[] = [
    {
      name: 'tab1',
      label: '待检验',
      content: (
        <div>
          <ProTable
            headerTitle="待检验数据查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={{
              ...tableSearchPublicConfig,
            }}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="button"
                icon={<CheckCircleOutlined />}
                onClick={() => {
                  setModalVisit2(true);
                }}
                type="primary"
              >
                检验标准
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const res = { ...params };
              const sorters = sortTran(sort);
              const filters = filterTranNew(res);
              const result = await getProductQualityByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              getlist();
              // 获取检验标准内容
              const standard = await getInspectionStandard(null);
              setstandardTableList(standard.data);
              // 筛选页面内容
              const temp_res = result.data.content.filter((item: any) => {
                return item.status == 0 || item.status == -1;
              });
              return {
                data: temp_res,
                total: temp_res.totalElements,
                success: result.success,
              };
            }}
            columns={columns}
            pagination={{
              defaultPageSize: 100,
              defaultCurrent: 1,
              pageSizeOptions: [100, 500, 1000],
              showSizeChanger: true,
            }}
            scroll={{ x: 1850, y: 'calc(100vh - 460px)' }}
            rowSelection={{}}
          />
        </div>
      ),
    },
    {
      name: 'tab2',
      label: '检验合格',
      content: (
        <div>
          <ProTable
            headerTitle="检验合格数据查询"
            actionRef={actionRef_2} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={{
              ...tableSearchPublicConfig,
            }}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="button"
                icon={<CheckCircleOutlined />}
                onClick={() => {
                  setModalVisit2(true);
                }}
                type="primary"
              >
                检验标准
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const res = { ...params, status: 1, inspection: 1 };
              const sorters = sortTran(sort);
              const filters = filterTranNew(res);
              const result = await getProductQualityByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              // console.log(result.data.content);
              getlist();
              // 获取检验标准内容
              const standard = await getInspectionStandard(null);
              setstandardTableList(standard.data);
              return {
                data: result.data.content,
                total: result.data.totalElementss,
                success: result.success,
              };
            }}
            columns={tested_columns.filter(function (item) {
              return item.dataIndex != 'memo';
            })}
            pagination={{
              defaultPageSize: 100,
              defaultCurrent: 1,
              pageSizeOptions: [100, 500, 1000],
              showSizeChanger: true,
            }}
            scroll={{ x: 2120, y: 'calc(100vh - 460px)' }}
            rowSelection={{}}
          />
        </div>
      ),
    },
    {
      name: 'tab3',
       label: '已驳回',
       content: (
         <div>
           <ProTable
             headerTitle="已驳回数据查询"
             actionRef={actionRef_3} //用于触发刷新操作等，看api
             rowKey="id" //表格行key的取值，可以是字符串或一个函数
             formRef={ref}
             search={{
               ...tableSearchPublicConfig,
             }}
             toolBarRender={(action, { selectedRows }) => [
               <Button
                 key="button"
                 icon={<CheckCircleOutlined />}
                 onClick={() => {
                   setModalVisit2(true);
                 }}
                 type="primary"
               >
                 检验标准
               </Button>,
             ]}
             request={async (params = {}, sort, filter) => {
               const res = { ...params, status: 1 };
               const sorters = sortTran(sort);
               const filters = filterTranNew(res);
               const result = await getProductQualityByPage({
                 ...params,
                 sorters: sorters,
                 filters: filters,
               });
               getlist();
                //获取检验标准内容
               const standard = await getInspectionStandard(null);
               setstandardTableList(standard.data);
                //筛选页面的值
               const temp_res = result.data.content.filter((item: any) => {
                 return item.inspection == '-1' || item.inspection == '2';
               });
               return {
                 data: temp_res,
                 total: temp_res.totalElements,
                 success: result.success,
               };
             }}
             columns={tested_columns}
             rowSelection={{}}
             pagination={{
               defaultPageSize: 100,
               defaultCurrent: 1,
               pageSizeOptions: [100, 500, 1000],
               showSizeChanger: true,
             }}
             scroll={{ x: 2120, y: 'calc(100vh - 460px)' }}
           />
         </div>
       ),
     },
  ];

  //定义编辑modalTabs的子结构的数组
  const tabList_modal: tabType[] = [
    {
      name: 'tab1',
      label: '详细信息',
      content: (
        <div style={{ height: 500, width: 1000 }}>
          <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
            <Descriptions title="" bordered column={2}>
              <Descriptions.Item label="工单编号">
                {quality_Record?.wo ? quality_Record?.wo : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="项目编号">
                {quality_Record?.projectCode ? quality_Record?.projectCode : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="项目名称">
                {quality_Record?.projectName ? quality_Record?.projectName : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="批次编号">
                {quality_Record?.batchPlanCode ? quality_Record?.batchPlanCode : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="当前批次">
                {quality_Record?.currentBatchCode
                  ? quality_Record?.currentBatchCode + '/' + quality_Record?.batchCount
                  : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="柜体类型">
                {quality_Record?.productType ? quality_Record?.productType : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="柜体编号">
                {quality_Record?.productCode ? quality_Record?.productCode : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="柜体描述">
                {quality_Record?.productDesc ? quality_Record?.productDesc : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="检验状态">
                {quality_Record?.status == 1
                  ? '已检验'
                  : quality_Record?.status == -1
                  ? '再检验'
                  : '待检验'}
              </Descriptions.Item>
            </Descriptions>
          </Space>
        </div>
      ),
    },
    {
      name: 'tab2',
      label: '检验表',
      content: (
        <div style={{ height: 500 }}>
          {/* 模板预览 */}
          <div className="templatebox" >
            <div clasName="templatebox_print" ref={componentRef }>
            <div className="pdName">{thetitle == '' ? '暂时没有工序检验表' : thetitle}</div>
            <div className="company">
              <div className="company_name">电柜管家</div>
              <div className="triangle"></div>
              <ul className="title_list">
                {thehead?.map((item, index) => {
                  return <li key={index}>{item?.name + ':' + item?.templateCustomItemValue}</li>;
                })}
                <li key={thehead.length + 1} hidden={quality_Record?.status == 0}>
                  检验时间: {quality_Record?.inspectTime}
                </li>
              </ul>
            </div>
            <ul className="list">
              {theitem?.map((item, index) => {
                if (item?.optionType == '单选') {
                  let selectOption = item?.rightOption.split('|');
                  if (item?.isDetailDes == '1') {
                    //有描述框
                    return (
                      <li key={index} className="list_item">
                        <div className="question_wrapper">
                          <div className="title">
                            {index + 1}|{item?.itemName}
                            {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                              ? ':（' + item?.inspectionMethod + '）'
                              : ''}
                          </div>
                          <div className="templatecontent">
                            <Input
                              className="detailinput"
                              defaultValue={item.descValue}
                              value={values[item.sortId]}
                              onChange={(e) => {
                                values[item.sortId] = e.target.value;
                                item.descValue = e.target.value;
                              }}
                              placeholder={'请输入描述内容'}
                            />
                          </div>
                        </div>
                        <div className="radio_wrapper">
                          <Radio.Group
                            options={selectOption}
                            defaultValue={item.rightValue}
                            onChange={(e) => {
                              item.rightValue = e.target.value;
                            }}
                          />
                        </div>
                      </li>
                    );
                  } else {
                    return (
                      <li key={index} className="list_item">
                        <div className="question_wrapper">
                          <div className="title">
                            {index + 1}|{item?.itemName}
                            {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                              ? ':（' + item?.inspectionMethod + '）'
                              : ''}
                          </div>
                        </div>
                        <div className="radio_wrapper">
                          <Radio.Group
                            options={selectOption}
                            defaultValue={item.rightValue}
                            onChange={(e) => {
                              item.rightValue = e.target.value;
                            }}
                          />
                        </div>
                      </li>
                    );
                  }
                } else if (item?.optionType == '多选') {
                  let thedescOption = item?.descOption.split('|');
                  if (item?.isExtendDes == '1') {
                    return (
                      <li key={index} className="list_item">
                        <div className="question_wrapper">
                          <div className="title">
                            {index + 1}|{item?.itemName}
                            {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                              ? ':（' + item?.inspectionMethod + '）'
                              : ''}
                          </div>
                          <div className="templatecontent">
                            <Checkbox.Group
                              options={thedescOption}
                              defaultValue={item.multiValue}
                              onChange={(e) => {
                                item.multiValue = e.target.value;
                              }}
                            />
                            <div className="other">
                              <div>
                                <span>*</span>如果没有合适选项，请文字描述:
                              </div>
                              <Input
                                className="detailinput"
                                defaultValue={item.multiDesValue}
                                value={values[item.sortId]}
                                onChange={(e) => {
                                  values[item.sortId] = e.target.value;
                                  item.multiDesValue = e.target.value;
                                }}
                                placeholder={'请输入描述内容'}
                              />
                            </div>
                          </div>
                        </div>
                      </li>
                    );
                  } else {
                    return (
                      <li key={index} className="list_item">
                        <div className="question_wrapper">
                          <div className="title">
                            {index + 1}|{item?.itemName}
                            {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                              ? ':（' + item?.inspectionMethod + '）'
                              : ''}
                          </div>
                          <div className="templatecontent">
                            <Checkbox.Group
                              options={thedescOption}
                              defaultValue={item.multiValue}
                              onChange={(e) => {
                                item.multiValue = e.target.value;
                              }}
                            />
                          </div>
                        </div>
                      </li>
                    );
                  }
                } else if (item?.optionType == '描述') {
                  return (
                    <li key={index} className="list_item">
                      <div className="question_wrapper">
                        <div className="title">
                          {index + 1}|{item?.itemName}
                          {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                            ? ':（' + item?.inspectionMethod + '）'
                            : ''}
                        </div>
                        <div className="templatecontent">
                          <TextArea
                            rows={3}
                            className="detailinput"
                            placeholder={'请输入描述内容'}
                            defaultValue={item.descValue}
                            value={values[item.sortId]}
                            onChange={(e) => {
                              values[item.sortId] = e.target.value;
                              item.descValue = e.target.value;
                            }}
                          />
                        </div>
                      </div>
                    </li>
                  );
                } else {
                  return (
                    <li key={index} className="list_item">
                      <div className="question_wrapper">
                        <div className="title">
                          {index + 1}|{item?.itemName}
                          {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                            ? ':（' + item?.inspectionMethod + '）'
                            : ''}
                        </div>
                        <div className="templatecontent">
                          <Input
                            className="detailinput"
                            placeholder={'请输入填空内容'}
                            defaultValue={item.descValue}
                            value={values[item.sortId]}
                            onChange={(e) => {
                              values[item.sortId] = e.target.value;
                              item.descValue = e.target.value;
                            }}
                          />
                        </div>
                      </div>
                    </li>
                  );
                }
              })}
            </ul>
            <ul className="list">
              <li className="list_item">
                <div className="question_wrapper">
                  <div className="title">备注</div>
                  <div className="templatecontent">
                    <Input
                      className="detailinput"
                      placeholder={'请输入填空内容'}
                      defaultValue={thetitleInfo.memo}
                      // value={values[item.sortId]}
                      onChange={(e) => {
                        // values[item.sortId] = e.target.value;
                        thetitleInfo.memo = e.target.value;
                      }}
                    />
                  </div>
                </div>
              </li>
            </ul>
            </div>
            <hr />
            <div style={{ width: 900, textAlign: 'center' }}>
              {/* <Button
                style={{ marginLeft: '20px' }}
                type="primary"
                hidden={thetitle == ''}
                onClick={() => {
                  // print_template(); //打印检验单
                  handle_print();
                }}
              >
                打印
              </Button> */}
              <ReactToPrint
                  trigger={() => <Button
                    style={{ marginLeft: '20px' }}
                    type="primary"
                    hidden={thetitle == ''}
                  >
                    打印
                  </Button>}
                  content={() => componentRef.current}
              />
              <Button
                style={{ marginLeft: '20px' }}
                type="primary"
                hidden={thetitle == ''}
                disabled={quality_Record?.status == 1}
                onClick={() => {
                  handleSave_template();
                }}
              >
                保存
              </Button>
              <Button
                style={{ marginLeft: '20px' }}
                type="primary"
                hidden={thetitle == ''}
                disabled={quality_Record?.status == 1}
                onClick={async () => {
                  //判断是否有未填项,flase有未填，true每项都填了
                  var submitisnull;
                  theitem.map((item: any, index: any) => {
                    if (
                      item.rightValue == null &&
                      item.multiValue == null &&
                      item.multiDesValue == null &&
                      item.descValue == null
                    ) {
                      //有一项是空
                      submitisnull = false;
                      // console.log(item, '该项为空');
                    }
                  });
                  if (submitisnull == false) {
                    message.warning('检验单有未填项');
                  } else {
                    // 获取当前用户、时间
                    const getuserlist = await viewBaseInfo(null);
                    setcurrentmemberid(getuserlist.data.id);
                    form.setFieldsValue({
                      inspectTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                      inspector: getuserlist.data.name,
                      inspectorId: getuserlist.data.id,
                    });
                    setsubmit_open(true);
                  }
                }}
              >
                提交
              </Button>
            </div>
          </div>
        </div>
      ),
    },
    {
      name: 'tab3',
      label: '检验附件',
      content: (
        <div style={{ height: 500 }}>
          <InspectionFileInfo theid={quality_Record?.id} thestatus={quality_Record?.status} />
        </div>
      ),
    },
    {
      name: 'tab4',
      label: '检验记录',
      content: (
        <div style={{ height: 500 }}>
          <ProTable
            headerTitle="检验记录"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={false}
            toolBarRender={(action, { selectedRows }) => []}
            request={async (params = {}, sort, filter) => {
              // const res = { ...params, wo: select_wo };
              const sorters = sortTran(sort);
              const filters = filterTranNew(params);
              const result = await getProductQualityInspectionByPage({
                pageEntity: {
                  ...params,
                  sorters: sorters,
                  filters: filters,
                },
                productQualityId: select_id,
              });
              // 筛选页面内容
              // const temp_res = result.data.content.filter((item: any) => {
              //   return item.status == 1||item.status == -1;
              // });
              // temp_res.map((item: any, index: any) => {
              //   item.memo = thetitleInfo.memo;
              // });
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={tested_columns.filter(function (item) {
              return item.valueType != 'option';
            })}
            scroll={{ x: 2100, y: 350 }}
            rowSelection={{}}
          />
        </div>
      ),
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <Tabs
        type="card"
        items={tabList.map((item, i) => {
          const id = String(i + 1);
          return {
            label: item.label,
            key: id,
            children: <div>{item.content}</div>,
          };
        })}
      />
      <Modal
        title="检验标准"
        visible={modalVisit2}
        onCancel={handleCancel}
        footer={[
          <Button key="back" onClick={() => handleCancel()}>
            关闭
          </Button>,
        ]}
        confirmLoading={confirmLoading2}
        width={1200}
        destroyOnClose
      >
        <div>
          <Table
            columns={standardColumns}
            bordered
            pagination={false}
            dataSource={standardTableList}
            rowKey={(record) => record.inspectionItem}
          />
        </div>
      </Modal>
      <Modal
        open={open}
        title="入厂检验"
        width={1300}
        onCancel={edit_handleCancel}
        destroyOnClose
        footer={null}
      >
        <Tabs
          tabPosition="top"
          items={tabList_modal.map((item, i) => {
            const id = String(i + 1);
            return {
              label: item.label,
              key: id,
              children: <div>{item.content}</div>,
            };
          })}
        />
      </Modal>
      <Modal
        title="确认检验"
        open={submit_open}
        onCancel={() => setsubmit_open(false)}
        onOk={inspection_Submit}
        confirmLoading={confirmLoading3}
        width={700}
        destroyOnClose
      >
        <div>
          <Form
            name="wrap"
            labelCol={{ flex: '110px' }}
            labelAlign="right"
            labelWrap
            form={form}
            wrapperCol={{ flex: 1 }}
            colon={false}
          >
            <Form.Item label="id" name="id" hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item
              label="检验人"
              name="inspector"
              rules={[{ required: true, message: '请输入检验人!' }]}
            >
              <Input disabled />
            </Form.Item>
            <Form.Item
              label="检验时间"
              name="inspectTime"
              rules={[{ required: true, message: '请输入检验时间!' }]}
            >
              <Input disabled />
            </Form.Item>
            <Form.Item
              label="检验结果"
              name="inspection"
              rules={[{ required: true, message: '请选择检验结果!' }]}
            >
              <Select
                defaultValue="选择检验结果"
                options={[
                  { value: 1, label: '合格' },
                  { value: -1, label: '不合格' },
                  { value: 2, label: '让步接收' },
                ]}
              />
            </Form.Item>
          </Form>
        </div>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default ProductQuality;
